package logic

import (
	"context"
	"errors"
	"video-hub/models/cache"
	"video-hub/models/mysql"
	"video-hub/pkg"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *videorpc.UpdatePasswordRequest) (*videorpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if err := user.FindPhone(mysql.DB, in.PhoneNum); err != nil {
		return nil, errors.New("该手机号不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()
	if result == "" {
		return nil, errors.New("短信验证码错误")
	}
	if user.Pwd != pkg.Md5(in.OldPwd) {
		return nil, errors.New("旧密码和数据库的密码不一致 重新输入")
	}

	if in.OldPwd == in.NewPwd {
		return nil, errors.New("新密码和旧密码一致不允许修改")
	}
	if in.NewPwd != in.CurePwd {
		return nil, errors.New("新密码和确认密码不一致重新输入")
	}

	user = mysql.User{
		Pwd:      in.NewPwd,
		NickName: in.NickName,
	}

	if err := user.UpdatePwd(mysql.DB, in.PhoneNum); err == nil {
		return nil, errors.New("密码已重置成功")
	}
	return &videorpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
